package com.langhang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.langhang.entity.TbSpecification;
import com.langhang.entity.TbSpecificationExample;
import com.langhang.mapper.TbSpecificationMapper;
import com.langhang.service.TbSpecificationService;
import com.langhang.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TbSpecificationServiceImpl implements TbSpecificationService {
    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;


    @Override
    public List<TbSpecification> findAll() {
        return tbSpecificationMapper.selectByExample(null);
    }

    // 分页查询
    @Override
    public PageResult<TbSpecification> findByPage(Integer page, Integer pageSize) {
        // 1. 开始分页
        PageHelper.startPage(page, pageSize);
        // 2. 开始查询数据
        List<TbSpecification> tbspecs = tbSpecificationMapper.selectByExample(null);
        // 3. 使用 PageInfo 存储分页信息
        PageInfo<TbSpecification> pageInfo = new PageInfo<>(tbspecs);
        // 4. 转换为 PageResult 对象
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public PageResult<TbSpecification> search(Integer page, Integer pageSize, String specName) {

        PageHelper.startPage(page,pageSize);

        TbSpecificationExample example = new TbSpecificationExample();

        TbSpecificationExample.Criteria criteria = example.createCriteria();
        if (StrUtil.isNotBlank(specName)) {
            criteria.andSpecNameLike("%" + specName + "%");
        }


        List<TbSpecification> tbspecs = tbSpecificationMapper.selectByExample(example);
        // 2.3 使用 PageInfo 存储分页信息
        Page<TbSpecification> tbspecPage = (Page<TbSpecification>) tbspecs;
        return new PageResult<>(tbspecPage.getResult(),tbspecPage.getTotal());
    }

    // 3. 添加学生
    @Override
    public boolean save(TbSpecification tbspec) {
        return tbSpecificationMapper.insert(tbspec) > 0;
    }
}